/*
 * For com.royal.art
 * Copyright [2015/11/7] By RICK
 */
package com.lerning.edu.manage.controller;

import com.lerning.edu.commons.util.CookieUtils;
import com.lerning.edu.manage.common.security.shiro.session.SessionDAO;
import com.lerning.edu.manage.context.GlobalContext;
import com.lerning.edu.manage.security.SystemAuthorizingRealm;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.manage.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * IndexController
 * index Controller
 * @author FCHEN
 * @date 2015/11/7
 */
@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

    @Autowired
    private SessionDAO sessionDAO;

    @RequiresPermissions("user")
    @RequestMapping(value = {"","/","index"})
    public String index(HttpServletRequest request, HttpServletResponse response){
        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();

        // 登录成功后，验证码计算器清零
        Utils.isValidateCodeLogin(principal.getLoginName(), false, true);

        if (logger.isDebugEnabled()){
            logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
        }

        // 如果已登录，再次访问主页，则退出原账号。
        if (GlobalContext.TRUE.equals(GlobalContext.getProperties("notAllowRefreshIndex"))){
            String logined = CookieUtils.getCookie(request, "LOGINED");
            if (StringUtils.isBlank(logined) || "false".equals(logined)){
                CookieUtils.setCookie(response, "LOGINED", "true");
            }else if (StringUtils.equals(logined, "true")){
                UserUtils.getSubject().logout();
                return "redirect:" + adminPath + "/login";
            }
        }
        return "index";
    }
}
